package org.ogv.spritesheet;

import org.ogv.OGV;

import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.TextureRegion;


public class SpriteSheetDef {
	//Members that reflect to Json
	public String[] 	resFile; //the first one lead to pack file, the second one to name in pack file
	public int[] 		colRow; //[x,y]
	public SpriteAnim[]	animDefs;	
	
	private Sprite[][]	_frames;
	
	/**
	 * resolve reference to runtime objects
	 */
	private void resolve() {
		//create frames that reference to actual Texture
		TextureRegion ss 		= OGV.asset.getTextureRegion(resFile);
		TextureRegion[][] trs 	= ss.split(ss.getRegionWidth()/colRow[0], ss.getRegionHeight()/colRow[1]);
		_frames = new Sprite[colRow[0]][colRow[1]];
		for(int i = 0; i < trs.length; ++i) {
			for(int j = 0; j < trs[i].length; ++j) {
				_frames[j][i] = new Sprite(trs[i][j]);
			}
		}
	}
	
	public Sprite getFrame(int idx) {
		//make sure the idx is right
		if(idx < 0 || idx > colRow[0] * colRow[1]) return null;
		
		//try to resolve
		if(_frames == null) resolve();
		
		//get the frame
		return _frames[idx % colRow[0]][idx / colRow[0]];
	}
	
	public boolean hasResolved() { return _frames != null; }
	
	public static class SpriteAnim {
		//Json reflect
		public float 	frameDuration;
		public byte[] 	frames;
		public boolean 	loop;

		public int getKeyFrame(float stateTime) {
			int curFrame = (int)(stateTime/frameDuration);
			if(loop) curFrame %= frames.length;
			else curFrame = curFrame >= frames.length ? frames.length - 1 : curFrame;
			return frames[curFrame];
		}
		
		public boolean isAnimEnded(float stateTime) {
			return stateTime > frameDuration * frames.length;
		}
	}
}
